<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
      :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="handleSave"
      @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad"
      @row-add="handleAddNew">
      <template #menu="{ row, index, size }">
        <el-button type="text" @click="handleView(row, index)">详情</el-button>
        <el-button type="text" @click="handleRemove(row)" v-if="row.status !== 1">下架</el-button>
        <el-button type="text" @click="handleAdd(row)" v-if="row.status === 1">上架</el-button>
        <el-button type="text" @click="handleEdit(row)">编辑</el-button>
        <el-button type="text" @click="handleDel(row)" :title="row.send_count > 0 ? '已发放的优惠券不可删除' : ''">删除</el-button>
      </template>

      <template slot-scope="{ row }" slot="status">
        <p v-if="row.status == 0" class="blue-normal">已上架</p>
        <p v-else-if="row.status == 1" class="green-normal">已下架</p>
        <p v-else-if="row.status == 2">未上架</p>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { mapGetters } from "vuex";
import { getList, updateStatus, delList, saveList } from "./api/couponList";
export default {
  data () {
    return {
      form: {
        title: "",
        amount: null, // 确保有amount字段
        days: 1,
        description: "",
        status: 2,
      },
      query: {},
      loading: false,
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      selectionList: [],
      option: {
        dialogWidth: "50%", // 调整对话框宽度
        dialogCustomClass: "coupon-dialog", // 添加自定义对话框类
        menuType: "button",
        height: "auto",
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: false,
        index: true,
        searchBtnText: "查询",
        searchBtnIcon: "查询",
        emptyBtnText: "重置",
        emptyBtnIcon: "重置",
        viewBtn: false,
        addBtn: true,
        addBtnText: "新建",
        addBtnIcon: "el-icon-plus",
        editBtn: false,
        editBtnText: "",
        selection: false,
        dialogClickModal: false,
        delBtn: false,
        delBtnText: "",
        labelWidth: 100,
        searchLabelWidth: 100,
        column: [
          {
            label: "关键词",
            prop: "关键词",
            search: true,
            hide: true,
            display: false,
          },
          {
            label: "优惠券id",
            prop: "id",
            width: 180,
            align: "center",
            display: false,
          },
          {
            label: "优惠券名称",
            prop: "title",
            width: 100,
            align: "center",
            span: 24, // 设置为24表示独占一行
            rules: [
              { required: true, message: "请输入优惠券名称", trigger: "blur" },
            ],
          },
          {
            label: "优惠券简介",
            prop: "intro",
            type: "textarea",
            size: "small",
            width: 160,
            span: 24, // 设置为24表示独占一行
            rules: [
              { required: true, message: "请输入优惠券简介", trigger: "blur" },
            ],
          },
          {
            label: "金额",
            prop: "amount", // 确保prop正确对应
            rules: [
              {
                required: true,
                message: "请输入抵扣金额",
                trigger: "blur",
              },
            ],
            span: 24,
            display: true, // 确保显示
          },
          {
            label: "有效期(天)",
            prop: "days",
            width: 100,
            align: "center",
            // display: false,
            rules: [
              { required: true, message: "请输入有效期", trigger: "blur" },
            ],
          },
          {
            label: "发放数量",
            prop: "send_count",
            width: 100,
            align: "center",
            display: false,
          },
          {
            label: "使用数量",
            prop: "use_count",
            width: 100,
            align: "center",
            display: false,
          },
          {
            label: "创建时间",
            type: "date",
            prop: "created_at",
            width: 180,
            align: "center",
            display: false,
          },
          {
            label: "最后操作人",
            prop: "operator_name",
            width: 180,
            align: "center",
            display: false,
          },
          {
            label: "上架状态",
            prop: "status",
            search: true,
            type: "select",
            display: false,
            dicData: [
              {
                label: "已上架",
                value: 0,
              },
              {
                label: "已下架",
                value: 1,
              },
              {
                label: "未上架",
                value: 2,
              },
            ],
          },
        ],
      },
      data: [],
      currentItemData: null,
      editDialogVisible: false,
      isEdit: false,

      editForm: {
        id: null,
        title: "",
        amount: 0,
        days: 1,
        description: "",
      },
      editRules: {
        title: [
          { required: true, message: "请输入优惠券名称", trigger: "blur" },
        ],
        amount: [
          { required: true, message: "请输入抵扣金额", trigger: "blur" },
        ],
        days: [{ required: true, message: "请输入有效期", trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    permissionList () {
      return {
        addBtn: this.vaildData(this.permission.user_add, true),
        viewBtn: this.vaildData(this.permission.user_view, true),
        delBtn: this.vaildData(this.permission.user_delete, true),
        editBtn: this.vaildData(this.permission.user_edit, true),
      };
    },
    ids () {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  methods: {
    // 详情相关
    handleView (data) {
      this.$router.push({
        path: "/coupon/detail",
        query: {
          id: data.id,
          days: data.days,
          title: data.title,
          amount: data.amount,
          status: data.status,
          send_count: data.send_count,
          use_count: data.use_count,
        },
      });
    },

    // 上架操作
    handleAdd (row) {
      this.$confirm("确定要上架此优惠券吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 保存原始状态以便回滚
          const originalStatus = row.status;

          // 立即更新本地数据（乐观更新）
          const updatedRow = { ...row, status: 0 };
          this.data = this.data.map((item) =>
            item.id === row.id ? updatedRow : item
          );

          updateStatus(row.id, { status: 0 })
            .then(() => {
              this.$message.success("上架成功");
              // 确保UI更新
              this.$forceUpdate();
            })
            .catch((error) => {
              // 回滚状态
              this.data = this.data.map((item) =>
                item.id === row.id ? { ...item, status: originalStatus } : item
              );
              this.$message.error("上架失败: " + (error.message || ""));
              console.error(error);
            });
        })
        .catch(() => {
          this.$message.info("已取消操作");
        });
    },

    // 下架操作
    handleRemove (row) {
      this.$confirm("确定要下架此优惠券吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 保存原始状态以便回滚
          const originalStatus = row.status;

          // 立即更新本地数据（乐观更新）
          const updatedRow = { ...row, status: 1 };
          this.data = this.data.map((item) =>
            item.id === row.id ? updatedRow : item
          );

          updateStatus(row.id, { status: 1 })
            .then(() => {
              this.$message.success("下架成功");
              // 确保UI更新
              this.$forceUpdate();
            })
            .catch((error) => {
              // 回滚状态
              this.data = this.data.map((item) =>
                item.id === row.id ? { ...item, status: originalStatus } : item
              );
              this.$message.error("下架失败: " + (error.message || ""));
              console.error(error);
            });
        })
        .catch(() => {
          this.$message.info("已取消操作");
        });
    },

    // 封装状态更新方法
    updateCouponStatus (id, params) {
      return updateStatus(id, params)
        .then((response) => {
          if (response.code === 200) {
            return Promise.resolve(response);
          } else {
            return Promise.reject(response.message || "操作失败");
          }
        })
        .catch((error) => {
          console.error("更新状态失败:", error);
          return Promise.reject(error);
        });
    },

    // 删除操作
    handleDel (row) {
      if (row.send_count > 0) {
        this.$message.warning("该优惠券已发放，无法删除");
        return;
      }
      this.$confirm("此操作将永久删除该优惠券, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delList(row.id)
            .then((res) => {
              this.$message.success("删除成功");
              this.onLoad(this.page); // 刷新列表
            })
            .catch((error) => {
              // 特别处理"已发放不可删除"的情况
              if (
                error.response &&
                error.response.data &&
                error.response.data.message === "优惠券已发放，不可删除"
              ) {
                this.$message.warning("该优惠券已发放，无法删除");
              } else {
                this.$message.error("删除失败: " + (error.message || ""));
              }
              console.error(error);
            });
        })
        .catch(() => {
          this.$message.info("已取消删除操作");
        });
    },

    // 编辑操作
    handleEdit (row) {
      if (row.send_count > 0) {
        this.$message.warning("已发放的优惠券不可编辑");
        return;
      }
      this.isEdit = true;
      this.editForm = {
        id: row.id,
        title: row.title,
        amount: row.amount,
        days: row.days,
        description: row.description || "",
      };
      this.editDialogVisible = true;
      this.$refs.crud.rowEdit(row, row.$index);
    },

    handleAddNew () {
      this.$refs.crud.rowAdd();
      // 确保表单有初始值
      this.form = {
        title: "",
        amount: 0,
        days: 1,
        description: "",
        status: 2,
      };
    },

    // 提交表单
    submitEditForm () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          const formData = { ...this.editForm };
          const apiMethod = this.isEdit ? updateList : addList; // 假设你有这两个API方法

          apiMethod(formData)
            .then((res) => {
              this.$message.success(this.isEdit ? "编辑成功" : "新增成功");
              this.editDialogVisible = false;
              this.onLoad(this.page); // 刷新列表
            })
            .catch((error) => {
              this.$message.error(
                (this.isEdit ? "编辑失败" : "新增失败") +
                ": " +
                (error.message || "")
              );
              console.error(error);
            });
        } else {
          return false;
        }
      });
    },

    handleEditDialogClose () {
      this.$refs.editForm.resetFields();
    },


    handleSave (row, done, loading) {
      this.$refs.crud.validate((valid) => {
        if (!valid) {
          loading(); // 保持加载状态
          return false;
        }

        // 准备提交数据
        const saveData = {
          ...row,
          status: typeof row.status === "undefined" ? 2 : row.status,
        };

        // 移除可能存在的空值
        Object.keys(saveData).forEach((key) => {
          if (saveData[key] === null || saveData[key] === undefined) {
            delete saveData[key];
          }
        });

        saveList(saveData)
          .then((res) => {
            this.$message.success(row.id ? "修改成功" : "新增成功");
            done(); // 必须调用done()关闭对话框
            this.onLoad(this.page); // 刷新列表
          })
          .catch((err) => {
            loading(); // 保持加载状态
            const errorMsg = err.message || err.msg || "操作失败";
            this.$message.error(errorMsg);
            console.error("操作失败:", err);
          });
      });
    },

    searchReset () {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange (params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange (list) {
      this.selectionList = list;
    },
    selectionClear () {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange (currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange () {
      this.onLoad(this.page, this.query);
    },
    onLoad (page, search = {}) {
      this.loading = true;
      let param = {
        page: page.currentPage,
        size: page.pageSize,
        ...this.query,
        ...search,
      };

      getList(param)
        .then((res) => {
          const responseData = res.data || res;
          console.log("responseData:", responseData);
          this.page.total = responseData.total || 0;
          this.data = responseData.list || [];
          this.loading = false;
          this.selectionClear();
        })
        .catch((error) => {
          this.loading = false;
          console.error("获取列表数据失败:", error);
          this.$message.error("获取列表数据失败");
        });

      // 在组件中调用
    },

    toggleSelection (rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    mounted () {
      this.onLoad(this.page);
    },
    rowUpdate (row, index, done, loading) {
      this.handleSave(row, done, loading); // 直接复用handleSave逻辑
    },
  },
};
</script>

<style lang="scss" scoped>
.blue-normal {
  color: #0e77d1;
  display: inline-block;
  display: flex;
  align-items: center;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    /**控制形状**/
    background-color: #0e77d1;
    /**控制图标颜色**/
    margin-right: 4px;
    /**图标与文字距离**/
  }
}

.green-normal {
  color: #00a854;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    /**控制形状**/
    background-color: #00a854;
    /**控制图标颜色**/
    margin-right: 4px;
    /**图标与文字距离**/
  }
}

.gray-normal {
  color: #aaaaaa;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    /**控制形状**/
    background-color: #aaaaaa;
    /**控制图标颜色**/
    margin-right: 4px;
    /**图标与文字距离**/
  }
}

.purple-normal {
  color: #8400ff;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    /**控制形状**/
    background-color: #8400ff;
    /**控制图标颜色**/
    margin-right: 4px;
    /**图标与文字距离**/
  }
}

.orange-normal {
  color: #f59a23;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    /**控制形状**/
    background-color: #f59a23;
    /**控制图标颜色**/
    margin-right: 4px;
    /**图标与文字距离**/
  }
}

::v-deep .coupon-dialog {
  background-color: #fff;
  /* 设置对话框背景为白色 */

  .el-dialog__header {
    border-bottom: 1px solid #eee;
    padding: 15px 20px;
    background-color: #fff;
    /* 头部背景也设为白色 */
  }

  .el-dialog__title {
    font-size: 16px;
    font-weight: bold;
  }

  .el-dialog__body {
    padding: 20px;
    background-color: #fff;
    /* 内容区域背景设为白色 */
  }

  /* 确保表单项一行一个 */
  .avue-form__row {
    display: block;
    /* 确保每行单独显示 */
    margin-bottom: 20px;
    width: 100%;

    .el-form-item {
      display: block;
      /* 表单项独占一行 */
      width: 100%;
    }

    .el-form-item__label {
      font-weight: normal;
      color: #666;
      width: 100%;
      /* 标签宽度 */
      text-align: left;
      float: none;
      /* 取消浮动 */
      display: block;
      padding: 0 0 10px 0;
    }

    .el-form-item__content {
      margin-left: 0 !important;
      /* 取消左边距 */
      width: 100%;
      display: block;
    }

    .el-input__inner,
    .el-textarea__inner {
      border-radius: 4px;
      width: 100%;
      /* 输入框宽度100% */
    }
  }

  /* 单选按钮组样式 */
  .el-radio-group {
    width: 100%;

    .el-radio {
      margin-right: 20px;
    }
  }

  /* 底部按钮区域 */
  .el-dialog__footer {
    text-align: center;
    padding: 15px 20px;
    border-top: 1px solid #eee;
    background-color: #fff;
    /* 底部背景设为白色 */

    .el-button {
      min-width: 100px;
      border-radius: 4px;
    }
  }
}

::v-deep .coupon-dialog {
  background-color: white;
  /* 设置背景为白色 */

  .el-dialog__header {
    border-bottom: 1px solid #eee;
    padding: 15px 20px;
    background-color: white;
    /* 头部背景也设为白色 */
  }

  .el-dialog__title {
    font-size: 14px;
    /* 减小标题字体大小 */
    font-weight: bold;
  }

  .el-dialog__body {
    padding: 20px;
    font-size: 13px;
    /* 减小主体字体大小 */
    background-color: white;
    /* 主体背景设为白色 */
  }

  .avue-form__row {
    margin-bottom: 15px;
    display: block;
    /* 确保每行只显示一个输入项 */
    width: 100%;

    .el-form-item {
      width: 100%;
      /* 表单项宽度100% */
      margin-right: 0;

      .el-form-item__label {
        font-weight: normal;
        color: #666;
        font-size: 13px;
        /* 减小标签字体大小 */
        width: 100% !important;
        /* 确保标签占满一行 */
        text-align: left;
        padding: 0 0 8px 0;
        /* 调整标签间距 */
      }

      .el-form-item__content {
        width: 100%;
        margin-left: 0 !important;

        .el-input__inner,
        .el-textarea__inner {
          border-radius: 4px;
          font-size: 13px;
          /* 减小输入框字体大小 */
          width: 100%;
        }
      }
    }
  }

  .el-form-item--small.el-form-item {
    margin-bottom: 15px;
    /* 增加表单项间距 */
  }

  .el-radio-group {
    width: 100%;

    .el-radio {
      margin-right: 20px;
      font-size: 13px;
      /* 减小单选按钮字体大小 */
    }
  }

  .el-dialog__footer {
    text-align: center;
    padding: 15px 20px;
    border-top: 1px solid #eee;
    background-color: white;
    /* 底部背景设为白色 */

    .el-button {
      min-width: 100px;
      border-radius: 4px;
      font-size: 13px;
      /* 减小按钮字体大小 */
      padding: 8px 15px;
      /* 调整按钮大小 */
    }
  }

  /* 确保对话框内容区域为白色 */
  .el-dialog {
    background-color: white;

    .avue-crud__dialog {
      background-color: white;
    }
  }

  /* 调整表单布局，确保每行一个元素 */
  .avue-form {
    .avue-form__row {
      flex-direction: column;

      .avue-form__item {
        width: 100%;
        margin-right: 0;
        margin-bottom: 15px;
      }
    }
  }
}
</style>
